<template>
  <div>
    <Row>
      <i-col span="24">
        <Card>
          <p slot="title">
            <Icon type="stats-bars"></Icon>
            用户列表
          </p>
          <a href="javascript:void(0)" slot="extra">
            <Button type="primary" size="small" @click="openNewUserModal">
              <Icon type="md-add"></Icon>&nbsp;新建用户
            </Button>
          </a>
          <div>
            <Form inline>
              <FormItem>
                <i-input type="text" v-model="keyword" style="width:200px" icon="ios-person" @on-change="findUser"
                         placeholder="检索用户"></i-input>
              </FormItem>
              <FormItem>
                <Button type="primary" @click="queryUser">查询</Button>
              </FormItem>
              <FormItem>
                <Button @click="cancelQuery">取消</Button>
              </FormItem>
            </Form>
          </div>
          <div>
            <Table size="small" :border="true" :columns="columns" :data="usersContainer" height="394"
                   :loading="loading"></Table>
          </div>
        </Card>
      </i-col>
    </Row>
    <Modal v-model="updateUserModal"
           title="更新用户信息"
           ok-text="更新"
           @on-ok="updateUser">
      <Row>
        <i-col span="24" style="padding: 10px">
          <Form :model="currentUser" label-position="top">
            <FormItem label="姓名" prop="realName">
              <i-input v-model="currentUser.realName" icon="ios-person" placeholder="姓名"></i-input>
            </FormItem>
            <FormItem label="邮箱">
              <i-input v-model="currentUser.email" icon="ios-mail" type="email" placeholder="邮箱"></i-input>
            </FormItem>
            <FormItem label="电话">
              <i-input v-model="currentUser.phone" icon="ios-call" type="text" placeholder="电话"></i-input>
            </FormItem>
          </Form>
        </i-col>
      </Row>
    </Modal>
    <Modal v-model="addUserModal"
           title="新建用户"
           ok-text="保存"
           @on-ok="addNewUser">
      <Row>
        <i-col span="12" style="border-right: 1px solid #eee;padding: 0 10px">
          <Form ref="newUser" :model="newUser" label-position="top" :rules="passwordValidate">
            <FormItem label="账号" prop="userName">
              <i-input v-model="newUser.userName" icon="ios-person" placeholder="账号"></i-input>
            </FormItem>
            <FormItem label="姓名" prop="realName">
              <i-input v-model="newUser.realName" icon="md-create" placeholder="姓名"></i-input>
            </FormItem>
            <FormItem label="电话">
              <Input v-model="newUser.phone" type="text" icon="ios-call" placeholder="电话"></Input>
            </FormItem>
          </Form>
        </i-col>
        <i-col span="12" style="padding: 0 10px">
          <Form ref="newUser" :model="newUser" label-position="top" :rules="passwordValidate">
            <FormItem label="密码" prop="password">
              <i-input v-model="newUser.password" type="password" icon="ios-key" placeholder="密码"></i-input>
            </FormItem>
            <FormItem label="再次输入密码" prop="checkedPassword">
              <i-input v-model="newUser.checkedPassword" type="password" icon="ios-key-outline"
                       placeholder="再次输入密码"></i-input>
            </FormItem>
            <FormItem label="邮箱">
              <i-input v-model="newUser.email" type="email" icon="ios-mail" placeholder="邮箱"></i-input>
            </FormItem>
          </Form>
        </i-col>
      </Row>
    </Modal>
    <Modal v-model="updatePasswordModal"
           title="修改密码"
           ok-text="保存"
           @on-ok="updatePassword">
      <Form ref="editPasswordForm" :model="editPasswordForm" :label-width="100" label-position="right"
            :rules="passwordValidate">
        <FormItem label="原密码" prop="oldPass">
          <i-input v-model="editPasswordForm.oldPass" type="password" placeholder="请输入新密码，至少6位字符"></i-input>
        </FormItem>
        <FormItem label="新密码" prop="newPass">
          <i-input v-model="editPasswordForm.newPass" type="password" placeholder="请输入新密码，至少6位字符"></i-input>
        </FormItem>
        <FormItem label="确认新密码" prop="rePass">
          <i-input v-model="editPasswordForm.rePass" type="password" placeholder="请再次输入新密码"></i-input>
        </FormItem>
      </Form>
    </Modal>
    <Modal v-model="roleRootModal" title="赋予角色" ok-text="保存" @on-ok="setRoleRoot" transfer>
      <Form label-position="top">
        <FormItem>
          <Select v-model="role" :transfer="true" prefix="ios-happy" placeholder="请选择角色">
            <Option v-for="item in roleList" :value="item.roleId" :key="item.roleId">{{ item.roleName }}</Option>
          </Select>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>
<script>
  export default {
    data() {
      const validePassword = (rule, value, callback) => {
        if (value !== this.newUser.password) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      };
      const valideRePassword = (rule, value, callback) => {
        if (value !== this.editPasswordForm.newPass) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      };
      return {
        loading: true,
        addUserModal: false,
        updateUserModal: false,
        updatePasswordModal: false,
        roleRootModal: false,
        keyword: '',
        editPasswordForm: {
          oldPass: '',
          newPass: '',
          rePass: ''
        },
        newUser: {
          userName: '',
          realName: '',
          password: '',
          checkedPassword: '',
          email: '',
          phone: '',
          company: '',
          department: '',
          position: '',
          sex: '0'
        },
        currentCompanys: [],
        currentDepartments: [],
        currentUser: {},
        usersContainer: [],
        data: [],
        columns: [
          {
            title: '姓名',
            key: 'realName',
            width: 120
          },
          {
            title: '账号',
            key: 'userName',
            width: 160
          },
          {
            title: '邮箱',
            key: 'email',
            render: (h, params) => {
              let txt = '暂未填写';
              if (params.row.email) {
                txt = params.row.email;
                return h('a', {
                  attrs: {
                    href: 'mailto:' + params.row.email
                  },
                  style: {
                    'color': '#9E9E9E'
                  }
                }, txt)
              } else {
                return h('span', {
                  style: {
                    'color': '#9E9E9E'
                  }
                }, txt)
              }
            }
          },
          {
            title: '公司',
            key: 'company',
            sortable: true,
            width: 150,
            render: (h, params) => {
              let txt = '暂未填写';
              if (params.row.company) {
                txt = params.row.company
              }
              return h('span', {
                style: {
                  'color': '#9E9E9E'
                }
              }, txt)
            }
          },
          {
            title: '电话',
            key: 'phone',
            width: 160,
            render: (h, params) => {
              let txt = '暂未填写';
              if (params.row.phone) {
                txt = params.row.phone
              }
              return h('span', {
                style: {
                  'color': '#9E9E9E'
                }
              }, txt)
            }
          },
          {
            title: '所属角色',
            key: 'roleName',
            width: 150,
            render: (h, params) => {
              return h('Tag',{
                props:{
                  color: params.row.roleId?'cyan':'default'
                }
              },params.row.roleName || '暂未授权')
            }
          },
          {
            title: '操作',
            key: 'action',
            width: 320,
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'success',
                    size: 'small',
                    disabled: params.row.enable === '1'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.openUpdateModal(params.row)
                    }
                  }
                }, '修改用户信息'),
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small',
                    disabled: params.row.enable === '1'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.openUpdatePasswordModal(params.row)
                    }
                  }
                }, '修改密码'),
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small',
                    disabled: params.row.enable === '1'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.setRole(params.row)
                    }
                  }
                }, '赋予角色'),
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small',
                    disabled: params.row.enable === '1'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.delete(params.row)
                    }
                  }
                }, '删除'),
              ])
            }
          },
        ],
        passwordValidate: {
          // 修改密码
          oldPass: [
            {required: true, message: '请输入原密码', trigger: 'blur'}
          ],
          newPass: [
            {required: true, message: '请输入新密码', trigger: 'blur'},
            {min: 6, message: '请至少输入6个字符', trigger: 'blur'},
            {max: 32, message: '最多输入32个字符', trigger: 'blur'}
          ],
          rePass: [
            {required: true, message: '请再次输入新密码', trigger: 'blur'},
            {validator: valideRePassword, trigger: 'blur'}
          ],
          // 新建
          userName: [
            {required: true, message: '请输入账号', trigger: 'blur'}
          ],
          realName: [
            {required: true, message: '请输入姓名', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入新密码', trigger: 'blur'},
            {min: 6, message: '请至少输入6个字符', trigger: 'blur'},
            {max: 32, message: '最多输入32个字符', trigger: 'blur'}
          ],
          checkedPassword: [
            {required: true, message: '请再次输入新密码', trigger: 'blur'},
            {validator: validePassword, trigger: 'blur'}
          ]
        },
        role: '',
        roleList: []
      }
    },
    methods: {
      findUser(e) {
        let val = e.target.value;
        if (val) {
          this.keyword = val;
          this.queryUser()
        } else {
          this.usersContainer = this.data
        }
      },
      // 拉取所有用户信息
      getUserList() {
        this.$api.userList().then(res => {
          this.data = res.data.userList;
          this.usersContainer = res.data.userList;
          this.loading = false
        })
      },
      openNewUserModal() {
        this.addUserModal = true;
      },
      setRoleRoot() {
        this.$api.setRole({
          userName: this.currentUser.userName,
          roleId: this.role
        }).then(res => {
          this.$Notice.success({
            title: res.data.msg
          });
          this.getUserList()
        })
      },
      queryUser() {
        let key = this.keyword;
        let array = [];
        let len = this.data.length;
        for (let i = 0; i < len; i++) {
          if (this.data[i].realName.indexOf(key) > -1) {
            array.push(this.data[i])
          }
        }
        this.usersContainer = array
      },
      cancelQuery() {
        this.keyword = '';
        this.getUserList();
      },
      // 新增用户
      addNewUser() {
        this.$refs['newUser'].validate((valid) => {
          if (valid) {
            let user = this.newUser;
            let obj = {
              userName: user.userName,
              realName: user.realName,
              password: user.password,
              email: user.email,
              phone: user.phone
            };
            this.$Spin.show({
              render: (h) => {
                return h('div', [
                  h('loading'),
                ])
              }
            });
            this.$api.addUser(obj).then(res => {
              this.$Spin.hide();
              if (res.code === 200) {
                this.$Notice.success({
                  title: '用户新建成功',
                });
                this.getUserList()
              } else {
                this.$Notice.error({
                  title: res.data.msg,
                });
              }
            })
          }
        });
      },
      // 更新用户信息
      openUpdateModal(row) {
        this.currentUser = row;
        this.updateUserModal = true;
      },
      updateUser() {
        let user = this.currentUser;
        let obj = {
          userName: user.userName,
          realName: user.realName,
          email: user.email,
          phone: user.phone
        };
        this.$api.updateUser(obj).then(res => {
          if (res.code === 200) {
            this.$Notice.success({
              title: res.data.msg,
            });
            this.getUserList()
          } else {
            this.$Notice.error({
              title: res.data.msg,
            });
          }
        })
      },
      // 修改密码
      openUpdatePasswordModal(row) {
        this.updatePasswordModal = true;
        this.editPasswordForm = {
          oldPass: '',
          newPass: '',
          rePass: ''
        };
        this.currentUser = row
      },
      updatePassword() {
        this.$refs['editPasswordForm'].validate((valid) => {
          if (valid) {
            let user = this.currentUser;
            let obj = {
              userName: user.userName,
              password: this.editPasswordForm.oldPass,
              newPassword: this.editPasswordForm.newPass
            };
            this.$api.resetPassword(obj).then(res => {
              this.editPasswordForm = {
                oldPass: '',
                newPass: '',
                rePass: ''
              };
              if (res.code === 200) {
                this.$Notice.success({
                  title: res.data.msg,
                });
                this.getUserList()
              } else {
                this.$Notice.error({
                  title: res.data.msg,
                });
              }
            })
          }
        });
      },
      // 删除用户
      delete(row) {
        this.$api.delUser({
          userName: row.userName
        }).then(res => {
          if (res.code === 200) {
            this.$Notice.success({
              title: res.data.msg,
            });
            this.getUserList()
          } else {
            this.$Notice.error({
              title: res.data.msg,
            });
          }
        })
      },
      // 赋予角色
      setRole(row) {
        this.role = '';
        this.currentUser = row;
        if (this.roleList.length > 0) {
          this.roleRootModal = true;
        } else {
          this.getRoleList()
        }
      },
      // 角色列表
      getRoleList() {
        this.$api.getRoleList().then(res => {
          if (res.code === 200) {
            this.roleList = res.data.roleList;
            this.roleRootModal = true;
          }
        })
      },
    },
    mounted() {
      this.getUserList()
    }
  }
</script>
